package com.cet.qz.unit01.chapter1_3;

import edu.princeton.cs.algs4.StdIn;

/**
 * @program: algorithm
 * @description: 后缀表达式求值
 * @author: 陈恩涛
 * @create: 2021-04-06 20:47
 **/
public class EvaluatePostfix {

    public static double evaluatePostfixExpression(String postfixExpression) {
        if (postfixExpression.length() == 0) {
            throw new RuntimeException("后缀表达式为空，无法计算！");
        }

        //操作数栈
        Stack<Double> vals = new Stack<>();

        for (int i = 0; i < postfixExpression.length(); i++) {
            String s = postfixExpression.substring(i, i + 1);
            double op2;
            switch (s) {
                case "+":
                    op2 = vals.pop();
                    vals.push(vals.pop() + op2);
                    break;
                case "-":
                    op2 = vals.pop();
                    vals.push(vals.pop() - op2);
                    break;
                case "*":
                    op2 = vals.pop();
                    vals.push(vals.pop() * op2);
                    break;
                case "/":
                    op2 = vals.pop();
                    vals.push(vals.pop() / op2);
                    break;
                default:
                    vals.push(Double.parseDouble(s));
            }
        }
        if (vals.size() != 1) {
            throw new RuntimeException("后缀表达式有误！");
        }
        return vals.pop();

    }

    public static void main(String[] args) {
        System.out.println("请输入一个后缀表达式：");
        System.out.println(evaluatePostfixExpression(StdIn.readString()));
    }
}
